<?php

namespace app\merchants\controller;

use app\BaseController;
use app\merchants\loader\Services;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Label\Alignment\LabelAlignmentCenter;
use Endroid\QrCode\Label\Font\NotoSans;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use think\Exception;
use yiqiniu\extend\facade\Logger;

/**
 *  通知
 */
class Callback extends BaseController
{

    /**
     * 接收通知
     */
    public function notify()
    {
        $notifyData = input('post.');

        $errorMsg = 'success';
        try {
            if (!isset($notifyData['notify_type'], $notifyData['notify_data']) || !is_array($notifyData['notify_data'])) {
                throw  new Exception('数据格式错误');
            }
            switch ($notifyData['notify_type']) {
                // 支付成功
                case 'transactions':
                    Services::Recharge()->pay_success($notifyData['notify_data'], $errorMsg);
                    break;
                default:
                    $errorMsg = '未知的类型';
                    break;
            }
        } catch (\Exception $e) {
            $errorMsg = $e->getMessage();
            if (!app()->isDebug()) {
                Logger::log(['request' => json_encode($notifyData, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE), 'result' => $errorMsg], true, 'callback');
            }
        }
        if (app()->isDebug()) {
            Logger::log(['request' => json_encode($notifyData, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE), 'result' => $errorMsg], true, 'callback');
        }
        echo $errorMsg;
        exit;

    }

    /**
     * 生成二维码
     */
    public function qrcode()
    {
        $data = request()->get('data');
        if (!empty($data)) {
            $data = base64_decode($data);
            $data = explode('|', $data);
        } else {
            $data = ['无内容-无效码', '无内容-无效码'];
        }
        $result = Builder::create()
            ->writer(new PngWriter())
            ->data($data[0])
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size(300)
            ->margin(10)
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin());
        if (isset($data[1])) {
            $result = $result->labelText($data[1])
                ->labelFont(new NotoSans(20))
                ->labelAlignment(new LabelAlignmentCenter());
        }

        $qrcode_data = $result->build()->getString();

        ob_clean();
        ob_start();

        return response($qrcode_data, 200, ['Content-Length' => strlen($qrcode_data)])->contentType('image/png');
    }
}